#include<iostream>
#include<vector>
#include<queue>
#include<utility>

using namespace std;
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& nums) {
        int m = nums.size(), n = nums[0].size();
        typedef pair<int, int> PII;
        queue<PII> q;
        int dx[4] = { 0, 0, 1, -1 };
        int dy[4] = { 1, -1, 0, 0 };
        vector<vector<int>> ret(m, vector<int>(n, -1));

        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                if (nums[i][j] == 0) {
                    q.push({ i, j });
                    ret[i][j] = 0;
                }

        while (!q.empty()) {
            int sz = q.size();
            for (int i = 0; i < sz; i++) {
                auto [a, b] = q.front();
                q.pop();
                for (int k = 0; k < 4; k++) {
                    int x = a + dx[k], y = b + dy[k];
                    if (x >= 0 && x < m && y >= 0 && y < n && ret[x][y] == -1) {
                        ret[x][y] = ret[a][b] + 1;
                        q.push({ x, y });
                    }
                }
            }
        }
        return ret;
    }
};